#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/wait.h>
#include<sys/socket.h>
#include<iostream>
#include<string.h>
#include<signal.h>
void workwait(int sig){
   wait(NULL);
}

int main(){
  //创建套接字 流式套接字
  //侦听套接字
  signal(SIGCHLD,workwait);
  int listen_sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
  if(listen_sockfd<0){
    perror("socket");
    return 0;
  }
  //绑定端口
  struct sockaddr_in addr ;
  addr.sin_family=AF_INET;
  addr.sin_port=htons(2927);
  addr.sin_addr.s_addr=inet_addr("0.0.0.0");
  int ret=  bind(listen_sockfd,(struct sockaddr*)&addr,sizeof(addr));
  if(ret<0){
    perror("bind");
    return 0;
  }
  ret = listen(listen_sockfd,2);
  if(ret<0){
    perror("listen");
    return 0;
  }

  //    printf("listen_sockfd %d\n",listen_sockfd);
  // printf("new_sockfd %d\n",new_sockfd);
  while(1){
  int new_sockfd =accept(listen_sockfd,NULL,NULL);
  if(new_sockfd<0){
    perror("accept");
    return 0;
  }
   int pid = fork();
    if(pid<0){
      //fail
      close(new_sockfd);
      continue;
    }else if(pid==0){
      //success
    char buf[1024]={0};

    ssize_t r_size=recv(new_sockfd,buf,sizeof(buf)-1,0);
    if(r_size<0){
      perror("recv");
      continue;
    }else if(r_size ==0){
      printf("client have shutdown\n");
      close(new_sockfd);
      break;
    }else{
      printf("buf is :%s \n",buf);
    }
    memset(buf,'\0',sizeof(buf));
    printf("please enter msg:");
    fflush(stdout);
    std:: cin>>buf;
    send(new_sockfd,buf,strlen(buf),0);
      
    }else{
      //dad

    }
  }
  close(listen_sockfd);
  return 0;
}
